﻿using Helper;
using HZY.Framework.DependencyInjection;
using Mapster;
using Model.Entity;
using Model.EntityInfo;

namespace DAL.Service
{
    public class UserService : BaseService<UserEntity>, IScopedSelfDependency
    {
        /// <summary>
        /// 用户登录
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public async Task<BaseResult<UserInfoModel>> LoginAsync(UserEntity user)
        {
            BaseResult<UserInfoModel> result = new BaseResult<UserInfoModel>();
            var item = await DB.SqlSugarClient.Queryable<UserEntity>()
                .Includes(e => e.RoleInfo)
                .Where(e => e.UserName == user.UserName)
                .FirstAsync();
            UserInfoModel res = item.Adapt<UserInfoModel>();
            if (res == null)
            {
                result.Code = SystemEnums.ResCode.Fail;
                result.Msg = "当前用户不存在，请检查用户名是否正确";
                result.Data = (UserInfoModel)new object();
                return result;
            }
            if (res.UserPassword != res.UserPassword)
            {
                result.Code = SystemEnums.ResCode.Fail;
                result.Msg = "密码不正确";
                result.Data = (UserInfoModel)new object();
                return result;
            }
            result.Code = SystemEnums.ResCode.Success;
            result.Msg = "登录成功！";
            result.Data = res;
            return result;
        }
        /// <summary>
        /// 新增用户
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public async Task<BaseResult<string>> CreateUserAsync(UserEntity user)
        {
            BaseResult<string> result = new BaseResult<string>();
            bool isExist = await ExistASync(e => e.UserName == user.UserName);
            if (isExist)
            {
                result.Code = SystemEnums.ResCode.Fail;
                result.Msg = "当前用户名已存在！";
                result.Data = "";
                return result;
            }
            int res = await InsertAsync(user);
            if (res == 0)
            {
                result.Code = SystemEnums.ResCode.Fail;
                result.Msg = "新增失败！";
                result.Data = "";
                return result;
            }
            result.Code = SystemEnums.ResCode.Success;
            result.Msg = "新增成功！";
            result.Data = "";
            return result;
        }

        /// <summary>
        /// 更新用户
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public async Task<BaseResult<string>> UpdataUserAsync(UserEntity user)
        {
            BaseResult<string> result = new BaseResult<string>();
            bool isExist = await ExistASync(e => e.Id == user.Id);
            if (!isExist)
            {
                result.Code = SystemEnums.ResCode.Fail;
                result.Msg = "用户不存在，请检查用户id！";
                result.Data = "";
                return result;
            }
            bool res = await UpdateAsync(user);
            if (!res)
            {
                result.Code = SystemEnums.ResCode.Fail;
                result.Msg = "更新失败！";
                result.Data = "";
                return result;
            }
            result.Code = SystemEnums.ResCode.Success;
            result.Msg = "更新成功！";
            result.Data = "";
            return result;
        }
        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public async Task<BaseResult<string>> DelUserAsync(UserEntity user)
        {
            BaseResult<string> result = new BaseResult<string>();
            bool res = await DeleteAsync(user);
            if (!res)
            {
                result.Code = SystemEnums.ResCode.Fail;
                result.Msg = "删除失败";
                result.Data = "";
                return result;
            }
            result.Code = SystemEnums.ResCode.Success;
            result.Msg = "删除成功！";
            result.Data = "";
            return result;
        }

        /// <summary>
        /// 获取用户列表
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public async Task<BaseResult<List<UserInfoModel>>> GetUserLidtAsync()
        {
            var list = await DB.SqlSugarClient.Queryable<UserEntity>()
               .Includes(e => e.RoleInfo)
               .ToListAsync();

            return new BaseResult<List<UserInfoModel>>()
            {
                Code = SystemEnums.ResCode.Success,
                Data = list.ToArray().Adapt<List<UserInfoModel>>()
            };
        }
        /// <summary>
        /// 获取用户有权限的路由
        /// </summary>
        /// <param name="RoleId"></param>
        /// <returns></returns>
        public async Task<BaseResult<List<RouteInfoModel>>> GetUserRoutesAsync(int RoleId)
        {
            var res = await DB.SqlSugarClient.Queryable<RouteBtRoleEntity>()
               .Where(it => it.RoleId == RoleId)
               .Includes(e => e.RouteInfo)
               .OrderBy(it => it.RouteInfo.Order, SqlSugar.OrderByType.Asc)
               .ToListAsync();
            List<RouteEntity> routes = new List<RouteEntity>();
            foreach (var item in res)
            {
                routes.Add(item.RouteInfo);
            }
            List<RouteInfoModel> routeInfoModels = BuildTree(routes);
            //List<RouteInfoModel> routeInfoModels = BuildTree([]);
            return new BaseResult<List<RouteInfoModel>>()
            {
                Code = SystemEnums.ResCode.Success,
                Data = routeInfoModels,
                Msg = string.Empty
            };
        }

        public List<RouteInfoModel> BuildTree(List<RouteEntity> nodes)
        {
            // 使用字典存储节点，以便快速查找
            List<RouteInfoModel> _nodes = nodes.Adapt<List<RouteInfoModel>>();
            var nodeMap = _nodes.ToDictionary(node => node.Id);
            var tree = new List<RouteInfoModel>();

            foreach (var node in _nodes)
            {
                // 如果是根节点（Pid=0），添加到树的根列表
                if (node.ParentId == 0)
                {
                    tree.Add(node);
                }
                else if (nodeMap.TryGetValue(node.ParentId, out var parent))
                {
                    // 否则添加到父节点的子列表
                    parent.Children.Add(node);
                }
            }

            return tree;
        }
    }
}
